package com.linian.pushforcampus.util;

import com.linian.pushforcampus.domain.PushConfigure;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * packageName com.linian.pushforcampus.util
 *
 * @author Lennon
 * @className WechatEventUtil
 * @date 2023/11/16
 * @description TODO
 */

public class WechatEventUtil {

    private static Logger log = LoggerFactory.getLogger(WechatEventUtil.class);


    /**
     * sha1加密转换
     *
     * @param input
     * @return
     */
    public static String encode(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error while encoding: " + e.getMessage());
            return null;
        }
    }


    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(inputStream);
            Element root = document.getRootElement();
            //root如下：org.dom4j.tree.DefaultElement@46c9c427 [Element: <xml attributes: []/>]
            List<Element> elements = root.elements();
            //elements中的内容包括请求道的xml数据包内容
            for (Element e : elements) {
                map.put(e.getName(), e.getStringValue());
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }

    public static boolean checkSignature(String signature, String timestamp, String nonce, String wechatToken) {
        String[] str = new String[]{wechatToken, timestamp, nonce};
        //排序
        Arrays.sort(str);
        //拼接字符串
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            buffer.append(str[i]);
        }
        //进行sha1加密
        String temp = encode(buffer.toString());
        //与微信提供的signature进行匹对
        return signature.equals(temp);
    }


}
